using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using Tryit.Models;

namespace Tryit.Services
{
    public class TemplateService
    {
        private readonly string _configPath;
        private readonly string _templatesDirectory;

        public TemplateService()
        {
            _configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config");
            _templatesDirectory = Path.Combine(_configPath, "templates");
            
            // 确保目录存在
            if (!Directory.Exists(_configPath))
                Directory.CreateDirectory(_configPath);
            if (!Directory.Exists(_templatesDirectory))
                Directory.CreateDirectory(_templatesDirectory);
        }

        /// <summary>
        /// 获取所有模板名称
        /// </summary>
        public List<string> GetAllTemplateNames()
        {
            try
            {
                var templateFiles = Directory.GetFiles(_templatesDirectory, "*.json");
                return templateFiles.Select(Path.GetFileNameWithoutExtension).ToList();
            }
            catch (Exception ex)
            {
                throw new Exception($"获取模板列表失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取所有模板
        /// </summary>
        public List<CompositionTemplate> GetAllTemplates()
        {
            try
            {
                var templates = new List<CompositionTemplate>();
                var templateFiles = Directory.GetFiles(_templatesDirectory, "*.json");

                foreach (var file in templateFiles)
                {
                    try
                    {
                        var template = LoadTemplateFromFile(file);
                        if (template != null)
                            templates.Add(template);
                    }
                    catch (Exception ex)
                    {
                        // 记录错误但继续处理其他文件
                        System.Diagnostics.Debug.WriteLine($"加载模板文件 {file} 失败: {ex.Message}");
                    }
                }

                return templates.OrderBy(t => t.Name).ToList();
            }
            catch (Exception ex)
            {
                throw new Exception($"获取所有模板失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 根据名称加载模板
        /// </summary>
        public CompositionTemplate LoadTemplate(string templateName)
        {
            try
            {
                var filePath = Path.Combine(_templatesDirectory, $"{templateName}.json");
                if (!File.Exists(filePath))
                    throw new FileNotFoundException($"模板文件不存在: {templateName}");

                return LoadTemplateFromFile(filePath);
            }
            catch (Exception ex)
            {
                throw new Exception($"加载模板失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 保存模板
        /// </summary>
        public async Task SaveTemplateAsync(CompositionTemplate template)
        {
            try
            {
                if (template == null)
                    throw new ArgumentNullException(nameof(template));

                if (string.IsNullOrWhiteSpace(template.Name))
                    throw new ArgumentException("模板名称不能为空");

                // 验证模板名称合法性
                var validName = GetValidFileName(template.Name);
                template.Name = validName;

                var filePath = Path.Combine(_templatesDirectory, $"{validName}.json");
                
                // 更新修改时间
                template.UpdateTime = DateTime.Now;

                var options = new JsonSerializerOptions
                {
                    WriteIndented = true,
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                };

                var json = JsonSerializer.Serialize(template, options);
                await File.WriteAllTextAsync(filePath, json);
            }
            catch (Exception ex)
            {
                throw new Exception($"保存模板失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 删除模板
        /// </summary>
        public async Task DeleteTemplateAsync(string templateName)
        {
            try
            {
                var filePath = Path.Combine(_templatesDirectory, $"{templateName}.json");
                if (!File.Exists(filePath))
                    throw new FileNotFoundException($"模板文件不存在: {templateName}");

                await Task.Run(() => File.Delete(filePath));
            }
            catch (Exception ex)
            {
                throw new Exception($"删除模板失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 复制模板
        /// </summary>
        public async Task<CompositionTemplate> CopyTemplateAsync(string sourceTemplateName, string newTemplateName)
        {
            try
            {
                var sourceTemplate = LoadTemplate(sourceTemplateName);
                if (sourceTemplate == null)
                    throw new Exception($"源模板不存在: {sourceTemplateName}");

                var newTemplate = new CompositionTemplate(newTemplateName, $"{sourceTemplate.Description} (副本)");
                
                // 复制元素到新的ObservableCollection
                foreach (var element in sourceTemplate.Elements)
                {
                    var newElement = new ElementComposition
                    {
                        Name = element.Name,
                        ActualValue = element.ActualValue,
                        TechnicalRequirement = element.TechnicalRequirement,
                        InternalRequirement = element.InternalRequirement,
                        Status = element.Status
                    };
                    newTemplate.Elements.Add(newElement);
                }

                await SaveTemplateAsync(newTemplate);
                return newTemplate;
            }
            catch (Exception ex)
            {
                throw new Exception($"复制模板失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 检查模板是否存在
        /// </summary>
        public bool TemplateExists(string templateName)
        {
            var filePath = Path.Combine(_templatesDirectory, $"{templateName}.json");
            return File.Exists(filePath);
        }

        /// <summary>
        /// 导入默认模板
        /// </summary>
        public async Task ImportDefaultTemplatesAsync()
        {
            try
            {
                var defaultTemplatePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources", "default_composition_templates.json");
                if (!File.Exists(defaultTemplatePath))
                    throw new FileNotFoundException("默认模板文件不存在");

                var json = await File.ReadAllTextAsync(defaultTemplatePath);
                var elements = JsonSerializer.Deserialize<List<ElementComposition>>(json);

                if (elements != null && elements.Any())
                {
                    var defaultTemplate = new CompositionTemplate("默认模板", "系统默认的成分模板");
                    
                    // 将元素添加到ObservableCollection
                    foreach (var element in elements)
                    {
                        defaultTemplate.Elements.Add(element);
                    }
                    
                    defaultTemplate.IsDefault = true;

                    await SaveTemplateAsync(defaultTemplate);
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"导入默认模板失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 从文件加载模板
        /// </summary>
        private CompositionTemplate LoadTemplateFromFile(string filePath)
        {
            try
            {
                var json = File.ReadAllText(filePath);
                var options = new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                };

                return JsonSerializer.Deserialize<CompositionTemplate>(json, options);
            }
            catch (Exception ex)
            {
                throw new Exception($"解析模板文件失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取有效的文件名
        /// </summary>
        private string GetValidFileName(string fileName)
        {
            var invalidChars = Path.GetInvalidFileNameChars();
            var validName = fileName;
            
            foreach (var invalidChar in invalidChars)
            {
                validName = validName.Replace(invalidChar, '_');
            }

            // 确保文件名不为空
            if (string.IsNullOrWhiteSpace(validName))
                validName = "template";

            return validName;
        }
    }
} 